package com.lingx.web.core.urihanlder;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.net.InetSocketAddress;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.springframework.stereotype.Component;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.lingx.utils.Utils;
import com.lingx.web.api.IApi;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
@Component
public class KaptchaHandler implements IUriHandler {
	public static Cache<String, String> YZM_CACHE = CacheBuilder.newBuilder().maximumSize(10000)
			.expireAfterWrite(5, TimeUnit.MINUTES).build();
	@Override
	public String getUri() {
		return "/kaptcha";
	}

	@Override
	public void handler(ChannelHandlerContext ctx, FullHttpRequest request) {
		try {
		Properties properties = new Properties();
		// properties.put("kaptcha.textproducer.char.length", "4");
		properties.put("kaptcha.border", "no");
		// properties.put("kaptcha.textproducer.font.color", "black");
		properties.put("kaptcha.textproducer.char.space", "5");
		properties.setProperty("kaptcha.image.width", "100");
		properties.setProperty("kaptcha.textproducer.font.size", "32");
		properties.setProperty("kaptcha.image.height", "40");
		// properties.put("kaptcha.obscurificator.impl",
		// "com.google.code.kaptcha.impl.FishEyeGimpy");
		Config config = new Config(properties);
		DefaultKaptcha dk = new DefaultKaptcha();
		dk.setConfig(config);
		String yzm=Utils.getRandomNumber(4);
		//String ip= request.headers().get("X-Real-IP")!=null?request.headers().get("X-Real-IP"):((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress();
		String ip=request.headers().get("X-Real-IP");//!=null?request.headers().get("X-Real-IP"):((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress()
		if(ip==null) {
			ip = request.headers().get("X-Forwarded-For");
			if(Utils.isNotNull(ip)){
			   ip = ip.split(",")[0];
			}
		}
		if(ip==null) {
			ip=((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress();
		}
		//System.out.println("kaptcha ip:"+ip);
		BufferedImage bi = dk.createImage(yzm);
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		YZM_CACHE.put(yzm, ip);
		ImageIO.write(bi, "png",  bout);
		byte[] responseBytes = bout.toByteArray();//Utils.readByteArrayFromResource(getPage(uri));
		bout.close();
		int  length= responseBytes.length;
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
				Unpooled.wrappedBuffer(responseBytes));
		response.headers().set("Content-Length", Integer.toString(length));
		response.headers().set("Content-Type", "image/png; charset=utf-8");
		response.headers().set("Access-Control-Allow-Origin", "*");
		response.headers().add("Access-Control-Allow-Methods", "GET,POST");
		ctx.writeAndFlush(response);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}

}
